package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class CommentsService {
    @Autowired
    private CommentApi commentApi;

    @Autowired
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate redisTemplate;

    //分页查询评理列表
    public PageResult findComments(String movementId, Integer page, Integer pagesize) {
        //1、调用API查询评论列表
        List<Comment> list = commentApi.findComments(movementId, CommentType.COMMENT, page, pagesize);
        //2、判断list集合是否存在
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //3、提取所有的用户id,调用UserInfoAPI查询用户详情
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //4、构造vo对象
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : list) {
            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo != null) {
                CommentVo vo = CommentVo.init(userInfo, comment);
                vos.add(vo);
            }
        }
        //5、构造返回值
        return new PageResult(page, pagesize, 0l, vos);
    }

    /**
     * 发布评论
     *
     * @param movementId
     * @param comment
     */
    public void saveComments(String movementId, String comment) {
        //1、获取操作用户id
        Long userId = UserHolder.getUserId();
        //2、构造Comment
        Comment comment1 = new Comment();
        ;
        comment1.setPublishId(new ObjectId(movementId));
        comment1.setCommentType(CommentType.COMMENT.getType());
        comment1.setContent(comment);
        comment1.setUserId(userId);
        comment1.setCreated(System.currentTimeMillis());
        //3、调用API保存评论
        Integer commentCount = commentApi.save(comment1);
        log.info("commentCount = " + commentCount);
    }

    /**
     * 动态点赞,喜欢与不喜欢
     */
    public Integer likeComment(String id, String denpens) {
        //通用字段
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(id));
        comment.setUserId(UserHolder.getUserId());
        //判断接受的参数是否包含点赞和喜欢的字段
        if (denpens.indexOf("like") != -1) {
            comment.setCommentType(CommentType.LIKE.getType());
            String key = Constants.MOVEMENTS_INTERACT_KEY + id;
            String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
            //1、调用API查询用户是否已点赞
            Boolean hasComment = commentApi.hasComment(id, UserHolder.getUserId(), CommentType.LIKE);
            //2、如果已经点赞，则取消点赞
            if (hasComment) {
                Integer count = commentApi.delete(comment);
                //4、拼接redis的key，删除点赞状态
                redisTemplate.opsForHash().delete(key, hashKey);
                return count;
            }
            //3、没有点赞则调用API保存数据到Mongodb
            comment.setCreated(System.currentTimeMillis());
            Integer count = commentApi.save(comment);
            //4、拼接redis的key，将用户的点赞状态存入redis
            redisTemplate.opsForHash().put(key, hashKey, "1");
            return count;
        } else //判断接受的参数是否包含点赞和喜欢的字段,此处因该为判断喜欢字段
            if (denpens.indexOf("love") != -1) {
            //4、拼接redis的key，
                String key = Constants.MOVEMENTS_INTERACT_KEY + id;
                String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
                comment.setCommentType(CommentType.LOVE.getType());
//1、调用API查询用户是否已喜欢
                Boolean hasComment = commentApi.hasComment(id, UserHolder.getUserId(), CommentType.LOVE);
                //2、如果已经喜欢，则取消喜欢
                if (hasComment) {
                    Integer count = commentApi.delete(comment);
                    redisTemplate.opsForHash().delete(key,hashKey);
                    return count;
                }
                //保存喜欢状态
                Integer count = commentApi.save(comment);
                redisTemplate.opsForHash().put(key,hashKey,"1");
                return count;
            }
            return null;
    }
}
